from django.shortcuts import render
from meiduo_mall.utils.meiduo_category import get_categories
from goods.models import SKU
from meiduo_mall.utils.breadcrumb import get_breadcrumb
from django.conf import settings
import os
from celery_tasks.main import app


@app.task(name='generate_static_detail_html')
def generate_static_detail_html(sku_id):
    try:
        sku = SKU.objects.get(pk=sku_id)
    except:
        return render(None, '404.html')
    # 三级分类
    category3 = sku.category

    # 频道分类
    categories = get_categories()

    # 面包屑导航
    breadcrumb = get_breadcrumb(category3)

    # sku对象数据：在前面已经根据编号查询
    # 当前库存商品的规格选项信息，结果如编号为16的库存商品对应的选项为：[0----6----16,1----7-----21]
    sku_options = sku.specs.order_by('spec_id')
    sku_option_list = [info.option_id for info in sku_options]

    # 标准商品spu
    spu = sku.spu

    # 查询所有的选项与库存商品的对应信息
    sku_option_dict = {}  # 键为选项列表，值为sku_id
    skus = spu.sku_set.filter(is_launched=True)
    for sku1 in skus:
        sku1_option_list = [info.option_id for info in sku1.specs.order_by('spec_id')]
        sku_option_dict[tuple(sku1_option_list)] = sku1.id
    # print(sku_option_dict)
    '''
    {
        (13,20):9,
        (14,20):10,
        (13,21):11,
        ....
    }
    '''

    # 规格===》选项===》库存商品编号
    specs = spu.specs.order_by('id')  # 6,7
    specs_list = []
    for index, spec in enumerate(specs):  # 6---0,7----1
        spec_dict = {
            'name': spec.name,
            'options': []
        }
        for option in spec.options.all():
            # 选项为钻雕金，编号为13,对应的规格是颜色，编号为6,对应的索引为0
            new_option_list = sku_option_list[:]  # [16,21]
            new_option_list[index] = option.id  # [13,21]
            t1 = tuple(new_option_list)
            # print(t1)
            sku_id = sku_option_dict.get(t1, 0)

            spec_dict['options'].append({
                'name': option.value,
                'selected': option.id in sku_option_list,
                'sku_id': sku_id
            })
        specs_list.append(spec_dict)

    # 热销排行
    # 其它：sku===>spu


    context = {
        'categories': categories,
        'breadcrumb': breadcrumb,
        'sku': sku,
        'spu': spu,
        'category_id': category3.id,
        'specs': specs_list
    }
    response = render(None, 'detail.html', context)
    html_str = response.content.decode()

    file_path = os.path.join(settings.BASE_DIR, 'static/details/%d.html' % sku.id)
    print(file_path)
    with open(file_path, 'w') as f1:
        f1.write(html_str)
